package com.zb.activemq.have_a_try;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * @Title 消息消费者
 * @Description 消息消费者是由会话创建的一个对象，它用于接收发送到目的地的消息。
 * Created by dongyuncong on 2017/6/23.
 */
public class Consumer {
    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        Session session;
        Destination destination;
        // 【消息消费者】
        MessageConsumer consumer;
        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_USER, ActiveMQConnection.DEFAULT_PASSWORD,
                "tcp://172.22.23.169:61616");
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(Boolean.TRUE, Session.CLIENT_ACKNOWLEDGE);
            // 获取session注意参数值FirstQueue是一个服务器的queue，须在在ActiveMq的console配置
            destination = session.createQueue("FirstQueue");
            session.recover();
            consumer = session.createConsumer(destination);
            while (true) {
                // 消息的消费可以采用以下两种方法之一：
                // • 同步消费。通过调用消费者的 receive 方法从目的地中显式提取消息。receive 方法可以一直阻塞到消息到达。
                // • 异步消费。客户可以为消费者注册一个消息监听器，以定义在消息到达时所采取的动作
                TextMessage message = (TextMessage) consumer.receive(500000);
                if (null != message) {
                    System.out.println("[消费者]消息:" + message.getText());
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != connection)
                    connection.close();
            } catch (Throwable ignore) {
            }
        }
    }
}
